package edu.ncsu.csc.csc454.project.gui.info_panel;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JPanel;

import edu.ncsu.csc.csc454.project.resources.Constants;
import edu.ncsu.csc.csc454.project.utilities.ImageUtilities;

/**
 * @author Team AW
 * @version 0.1
 */
@SuppressWarnings("serial")
public class TowerBars extends JPanel {

    private BufferedImage[] bars;

    private int             currentBar;

    private Random          rand = new Random();

    public TowerBars() {
        initBars();
        initThread();
        setOpaque(false);
        setPreferredSize(new Dimension(bars[0].getWidth(), bars[0].getHeight()));
    }

    private void initBars() {
        bars = new BufferedImage[Constants.BARS.length];

        for (int i = 0; i < bars.length; i++) {
            bars[i] = ImageUtilities.loadImage(Constants.BARS[i]);
        }

        currentBar = rand.nextInt(6);
    }

    private void initThread() {
        Thread t = new BarSelector();
        t.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        ((Graphics2D) g).drawImage(bars[currentBar], null, 0, 0);
    }

    private class BarSelector extends Thread {

        @Override
        public void run() {
            while (true) {
                currentBar += (rand.nextBoolean()) ? 1 : -1;

                if (currentBar < 0) {
                    currentBar = 0;
                }

                if (currentBar > bars.length - 1) {
                    currentBar = bars.length - 1;
                }

                repaint();

                try {
                    sleep((rand.nextInt(6) + 1) * 500);
                } catch (InterruptedException e) {}
            }
        }
    }
}
